const moment = require('moment');
const crypto = require('crypto');
const url = require('url');
const urlencode = require('urlencode');

module.exports = function signature(accessKey,secretKey,method,baseUrl,path,param){
    let myUrl =url.parse(baseUrl)
    let host = myUrl.host;
    var timestamp = moment().utcOffset('Z').format('YYYY-MM-DDTHH:mm:ss')
    let defaultParam = {
        AccessKeyId:accessKey,
        SignatureVersion:'2',
        SignatureMethod:'HmacSHA256',
        Timestamp:timestamp,
    }
    let allParam = Object.assign({}, defaultParam, param);

    let str = `${method}\n${host}\n${path}\n`;

    Object.keys(allParam).sort().forEach(function(key) {
        str += key + '=' + urlencode.encode(allParam[key]) + '&';
    });
    str = str.substring(0,str.length - 1);

    let hmac = crypto.createHmac('sha256', secretKey).update(str);
    let signature = hmac.digest('base64');
    allParam.Signature = signature;
    // console.log(allParam)
    let result = url.format({
        protocol: 'https',
        hostname: host,
        pathname: path,
        query: allParam
      });
    return result;
}

